import { _decorator, Component, Sprite, Node, SpriteFrame, v3, Color, UITransform, Graphics, EventTouch, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

/**Line */
@ccclass('SS_Line')
export default class SS_Line extends Component {
    static Instance: SS_Line;

    // @property({ type: Sprite })
    // public Sprite_bg: Sprite | null = null;

    g: Graphics;
    p_start;

    canMove: boolean = true;
    sibling;

    onLoad() {
        SS_Line.Instance = this;

        this.Init();
    }

    Init() {
        this.g = this.getComponent(Graphics);
        this.g.lineWidth = 10;
        this.g.fillColor.fromHEX('#ff0000');

        // this.AddListener();
    }

    AddListener() {
        this.node.on(Node.EventType.TOUCH_START, this.TOUCH_START, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.TOUCH_MOVE, this);
        this.node.on(Node.EventType.TOUCH_END, this.TOUCH_END, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.TOUCH_END, this);
    }

    async TOUCH_START(event: EventTouch) {
        let pos = event.getUILocation();
        let p = this.convertToNodeSpaceAR(pos);
        // console.info("onTouchStart pos x=" + pos.x + " y=" + pos.y);
        // console.info("onTouchStart out x=" + out.x + " y=" + out.y);

        console.log(`TOUCH_START-------`);

        this.p_start = p;

        this.g.clear();
        this.g.lineWidth = 10;
        this.g.fillColor.fromHEX('#ff0000');
        this.g.moveTo(this.p_start.x, this.p_start.y);

        // this.g.stroke();
    }

    TOUCH_MOVE(event: EventTouch) {
        // console.log(`TOUCH_MOVE-------`);

        let pos = event.getUILocation();
        let p = this.convertToNodeSpaceAR(pos);
        // console.info("onTouchMove pos x=" + pos.x + " y=" + pos.y);
        // console.info("onTouchMove out x=" + out.x + " y=" + out.y);

        this.g.clear();
        this.g.moveTo(this.p_start.x, this.p_start.y);
        this.g.lineTo(p.x, p.y);
        this.g.stroke();
    }

    async TOUCH_END(t) {
        console.log("TOUCH_END");
    }

    /**
     * 坐标转换
     */
    private convertToNodeSpaceAR(pos: Vec2): Vec3 {
        let out = new Vec3();
        this.node.getComponent(UITransform)?.convertToNodeSpaceAR(new Vec3(pos.x, pos.y, 0), out);
        return out;
    }

    // this.g.moveTo(-40, 0);
    // this.g.lineTo(0, -80);
    // this.g.lineTo(40, 0);
    // this.g.lineTo(0, 80);
    // this.g.close();
    // this.g.stroke();
    // g.fill();
}